package com.ks.user.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ks.core.base.OperationContext;
import com.ks.core.constant.Const;
import com.ks.core.dto.SearchCriteriaBase;
import com.ks.core.exception.BizExceptionEnum;
import com.ks.core.exception.GunsException;
import com.ks.core.util.MD5Util;
import com.ks.core.util.StringUtil;
import com.ks.core.util.ToolUtil;
import com.ks.user.dao.OrgBaseMapper;
import com.ks.user.dao.OrgTenantMapper;
import com.ks.user.dao.RedisDao;
import com.ks.user.dao.UserBaseMapper;
import com.ks.user.entity.OrgBase;
import com.ks.user.entity.OrgEmployee;
import com.ks.user.entity.OrgTenant;
import com.ks.user.entity.UserBase;
import com.ks.user.service.IOrgBaseService;
import com.ks.user.service.IOrgEmployeeService;
import com.ks.user.service.IUserBaseService;
import com.ks.user.service._ServiceBase;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织机构表 服务实现类
 * </p>
 *
 * @author kingdee123
 * @since 2020-11-30
 */
@Service
public class OrgBaseServiceImpl extends _ServiceBase<OrgBaseMapper, OrgBase> implements IOrgBaseService {
    @Resource
    private OrgBaseMapper orgBaseMapper;
    @Resource
    private OrgTenantMapper orgTenantMapper;
    @Resource
    private IOrgEmployeeService orgEmployeeService;
    @Resource
    private UserBaseMapper userBaseMapper;
    @Resource
    private RedisDao redis;
    @Resource
    private IUserBaseService userBaseService;


    @Override
    public int setTenantAdmin(OperationContext operationContext, int tenantId) {
        OrgTenant orgTenant = orgTenantMapper.selectById(tenantId);
        if (ToolUtil.isNotEmpty(orgTenant)) {
            if (orgTenant.getSexamineStatus() != Const.DEL_FLAG_DEL){
                throw new GunsException("请先通过审核后在设置成为管理员");
            }
            int i = userBaseService.setTenantAdmin(operationContext, orgTenant.getIcontactsMobile(), orgTenant.getIName(), orgTenant.getId(), orgTenant.getOrgID());
            return i;
        }
        return 0;
    }


    @Override
    public int addOrgBase(OperationContext operationContext, OrgBase orgBase) {
        UserBase userBase = this.LoadUserDataByToken(operationContext.getToken());
        if (ToolUtil.isNotEmpty(userBase)) {
            orgBase.setSStatus(Const.DEL_FLAG_NORMAL);
            orgBase.setCreateUserID(operationContext.getUserId().intValue());
            orgBase.setUpdateUserID(operationContext.getUserId().intValue());
            orgBase.setDataType(userBase.getDataType());
            orgBase.setTenantID(operationContext.getTenantId().intValue());
            orgBase.setOrgID(operationContext.getOrgId().intValue());
            Integer insert = orgBaseMapper.insert(orgBase);
            return insert;
        }
        return 0;
    }

    @Override
    public int insetOrgBase(OperationContext operationContext, String iOrgCode, String iMechanismName, int tenantId) {
        OrgBase orgBase = new OrgBase();
        orgBase.setIOrgCode(iOrgCode);
        orgBase.setIMechanismName(iMechanismName);
        orgBase.setIMechanismType(Const.OrgBase.ORGANIZATION_TYPE);
        orgBase.setIMechanismCode(iOrgCode);
        orgBase.setCMicroAppAllow(Const.OrgBase.IS_AUTHORIZATION);
        orgBase.setSStatus(Const.OrgBase.ORG_BASE_ENABLE);
        orgBase.setCreateUserID(operationContext.getUserId().intValue());
        orgBase.setTenantID(tenantId);
        orgBaseMapper.insert(orgBase);
        return orgBase.getId();
    }

    @Override
    public int updateOrgBase(OperationContext operationContext, OrgBase orgBase) {
        if (orgBase.getSStatus() == 1) {
            if (ToolUtil.isEmpty(orgBase.getISuperiorCode())) {
                throw new GunsException(BizExceptionEnum.ORG_BASE_ERROR);
            }
        }
        orgBase.setUpdateUserID(operationContext.getUserId().intValue());
        Integer integer = orgBaseMapper.updateById(orgBase);
        return integer;
    }

    @Override
    public Map<String, Object> getTree(int tenantId) {
        Map<String, Object> map = new HashMap<>();
        EntityWrapper<OrgBase> wrapper = new EntityWrapper<>();
        OrgBase orgBase = new OrgBase();
        orgBase.setTenantID(tenantId);
        orgBase.setSStatus(Const.OrgBase.ORG_BASE_ENABLE);
        wrapper.setEntity(orgBase);
        List<OrgBase> orgBases = orgBaseMapper.selectList(wrapper);
        if (ToolUtil.isNotEmpty(orgBases)) {
            Object objtree = CreateOrgTree(orgBases.get(0), orgBases);
            map.put("object", objtree);
        }
        return map;
    }

    private static class OrgTreeNode {
        public OrgTreeNode(OrgBase rootNode) {
            this.orgCode = rootNode.getIOrgCode();
            this.OrgName = rootNode.getIMechanismName();
            this.orgId = rootNode.getId();
            this.iMechanismCode = rootNode.getIMechanismCode();
            this.iMechanismType = rootNode.getIMechanismType();

        }

        public Integer orgId;
        public String orgCode;
        public String OrgName;
        public String iMechanismCode;
        public Integer iMechanismType;
        public List<OrgTreeNode> ChildList = new ArrayList<>();
    }

    private OrgTreeNode CreateOrgTree(OrgBase rootNode, List<OrgBase> orgBaseList) {
        OrgTreeNode obj = new OrgTreeNode(rootNode);
        List<OrgBase> collect = orgBaseList.stream().filter(item -> ToolUtil.isNotEmpty(item.getISuperiorCode()) && item.getISuperiorCode().equals(rootNode.getIOrgCode())).collect(Collectors.toList());
        if (collect == null) {
            return obj;
        } else {
            for (OrgBase orgBase : collect) {
                OrgTreeNode objChild = CreateOrgTree(orgBase, orgBaseList);
                obj.ChildList.add(objChild);
            }
        }
        return obj;
    }


    @Override
    public Map<String, Object> getOrgBaseList(OperationContext operationContext,SearchCriteriaBase searchCriteriaBase) {
        Map<String, Object> map = new HashMap<>();
        EntityWrapper<OrgBase> wrapper = new EntityWrapper<>();
        OrgBase base = new OrgBase();
        base.setDelMark(Const.DEL_FLAG_NORMAL);
        base.setTenantID(operationContext.getTenantId().intValue());
        ArrayList<SearchCriteriaBase.matchField> fields = searchCriteriaBase.getFields();
        if (ToolUtil.isNotEmpty(fields)) {
            for (SearchCriteriaBase.matchField field : fields) {
                if ("iOrgCode".equals(field.getName())) {
                    wrapper.setEntity(base);
                    wrapper.like("iMechanismCode", field.getValue());
                }
            }
            Integer integer = orgBaseMapper.selectCount(wrapper);
            map.put("count", integer);
            List<OrgBase> orgBases = orgBaseMapper.selectPage(new Page(searchCriteriaBase.getPageIndex(), searchCriteriaBase.getLimit()), wrapper);
            map.put("orgBases", orgBases);
        }

        return map;
    }

    @Override
    public List<OrgBase> getList(OperationContext operationContext) {
        EntityWrapper<OrgBase> wrapper = new EntityWrapper<>();
        OrgBase orgBase = new OrgBase();
        orgBase.setTenantID(operationContext.getTenantId().intValue());
        orgBase.setDelMark(Const.DEL_FLAG_NORMAL);
        wrapper.setEntity(orgBase);
        List<OrgBase> orgBases = orgBaseMapper.selectList(wrapper);
        return orgBases;
    }


    public List<OrgBase> getOrgBase(String OrgCode) {
        EntityWrapper<OrgBase> wrapper = new EntityWrapper<>();
        OrgBase orgBase = new OrgBase();
        orgBase.setISuperiorCode(OrgCode);
        wrapper.setEntity(orgBase);
        List<OrgBase> orgBases = orgBaseMapper.selectList(wrapper);
        return orgBases;
    }


    @Override
    public int updateTenantServiceStatus(int tenantId, Integer ServiceStatus) {
        OrgTenant orgTenant = orgTenantMapper.selectById(tenantId);
        if (ToolUtil.isNotEmpty(orgTenant)) {
            orgTenant.setCOpening(ServiceStatus);
            Integer integer = orgTenantMapper.updateById(orgTenant);
            return integer;
        }
        if (ServiceStatus == Const.DEL_FLAG_DEL) {
            //说明租户服务被关闭
            redis.delKey("1");
        }
        return 0;
    }

    @Override
    public int addUserBase(OperationContext operationContext, int employeeId) {
        UserBase userBase = this.LoadUserDataByToken(operationContext.getToken());
        String Salt = StringUtil.getStringRandom(8);
        if (ToolUtil.isNotEmpty(userBase)) {
            OrgEmployee orgEmployee = orgEmployeeService.getOrgEmployee(employeeId);
            if (ToolUtil.isNotEmpty(orgEmployee)) {
                UserBase base = new UserBase();
                base.setITel(orgEmployee.getIMobile());
                base.setIUserName(orgEmployee.getIMobile());
                base.setIRealName(orgEmployee.getIName());
                base.setCSalt(Salt);
                base.setIPassWord(MD5Util.getMD5(MD5Util.getMD5("666666") + Salt));
                base.setIfavatar(orgEmployee.getIImage());
                base.setINickName(orgEmployee.getIName());
                OrgTenant orgTenant = orgTenantMapper.selectById(operationContext.getTenantId());
                if (ToolUtil.isNotEmpty(orgTenant)) {
                    base.setISign(orgTenant.getIName() + "-" + orgEmployee.getIName());
                }
                base.setCUserType(Const.SysUser.UserBaseType);
                base.setTenantID(Integer.valueOf(operationContext.getTenantId().intValue()));
                base.setOrgSubID(orgEmployee.getCOrgNodeID());
                base.setDataType(this.LoadUserDataByToken(operationContext.getToken()).getDataType());
                Integer insert = userBaseMapper.insert(base);
                orgEmployee.setIUserID(base.getId());
                orgEmployeeService.updateById(orgEmployee);
                return insert;
            }
        }
        return 0;
    }


}
